package com.lanlian.commonlib.network;

import com.android.volley.error.VolleyError;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.common.SystemConfig;
import com.lanlian.commonlib.dao.DBManager;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.volleylib.RequestListener;

public class NetWorkImpl implements RequestListener {

    private INetWorkCallback callBack;

    public NetWorkImpl(INetWorkCallback callBack) {
        this.callBack = callBack;
    }

    @Override
    public void onSuccess(Object response) {
        if (callBack != null) {
            //资讯接口 PHP 过来的特殊处理了
            if (response.getClass().equals(String.class)) {
                callBack.onSuccess(response);
                return;
            }
            BaseResponse baseResponse = (BaseResponse) response;
            if (SystemConfig.HTTP_NETWORK_SUCCESS.equals(baseResponse.getCode())) {
                callBack.onSuccess(response);
            } else {
                if (SystemConfig.HTTP_TOKEN_EXPIRE.equals(baseResponse.getCode())) {
                    DBManager.getInstance().setLoginOut();
                    EventBusUtils.post(new EventMessage(EventCode.EVENT_LOGIN_OUT_REFRESH));
                    EventBusUtils.post(new EventMessage(EventCode.EVENT_FUCK_OUT_REFRESH));
                }
                callBack.onFail(baseResponse);
            }
        }
    }

    @Override
    public void onFailed(VolleyError error) {
        if (callBack != null) {
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.setMsg("服务器连接失败，请稍后再试");
            baseResponse.setCode(SystemConfig.HTTP_NETWORK_ERROR);
            callBack.onFail(baseResponse);
        }
    }
}
